<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container" v-if="companySelectVisible">
          <el-select v-model="company" filterable placeholder="请选择公司" @change="handleCompanyChange">
            <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
            />
          </el-select>
        </div>
        <div class="head-container">
          <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              highlight-current
              default-expand-all
              draggable
              @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="成员编码" prop="staffCode">
            <el-input
                v-model="queryParams.staffCode"
                placeholder="请输入成员编码"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="成员名称" prop="staffName">
            <el-input
                v-model="queryParams.staffName"
                placeholder="请输入成员名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
                v-model="queryParams.mobile"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间" style="width: 308px;">
            <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="成员编码" align="center" key="staffCode" prop="staffCode" v-if="columns[0].visible" />
          <el-table-column label="成员名称" align="center" key="staffName" prop="staffName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="手机号" align="center" key="mobile" prop="mobile" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="性别" align="center" key="gender" :formatter="genderFormatter" v-if="columns[4].visible" />
          <el-table-column label="部门" align="center" :formatter="deptFormatter" v-if="columns[4].visible" />
          <el-table-column label="邮箱" align="center" key="email" prop="email" v-if="columns[5].visible" width="120" />
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                    type="primary"
                    link
                    icon="Edit"
                    @click="handleUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                    type="primary"
                    link
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="成员编码" prop="staffCode">
              <el-input v-model="form.staffCode" disabled maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                  v-model="form.departmentId"
                  :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="请选择归属部门"
                  check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="成员名称" prop="staffName">
              <el-input v-model="form.staffName" placeholder="请输入成员名称" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option label="男" :value="1"/>
                <el-option label="女" :value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Staff">
import {useRouter} from "vue-router";
import {getCurrentInstance, reactive, toRefs} from "vue";
import {getStaff, listCompany, listDept, listStaff, saveStaff} from "../../../api/ab/ab";

const router = useRouter();
const { proxy } = getCurrentInstance();
const company = ref('')
const companySelectVisible = ref(false)
const companyList = ref([]);
const deptList = ref([]);
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);

// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);
function getCompanyList() {
  listCompany().then(res => {
    companyList.value = res.ds.content;
    if(companyList.value.length > 0) {
      company.value = companyList.value[0].id
      queryParams.value.companyId = companyList.value[0].id
      queryParams.value.department = []
      // 查询公司部门
      getDeptList(companyList.value[0].id)
      getList()
    }
    if(companyList.value.length > 1) {
      companySelectVisible.value = true
    }
  });
}
function getDeptList(companyId) {
  listDept({"companyId":companyId}).then(res => {
    deptList.value = res.ds
    const initDeptTree = (parentNode, parentId) => {
      const _deptList = deptList.value.filter(dept => dept.parentId === parentId)
      if(_deptList.length > 0) {
        const node = []
        _deptList.forEach(dept => {
          let _node = {
            id:dept.id,
            label:dept.deptName,
            children:[]
          }
          parentNode.push(_node)
          initDeptTree(_node.children,dept.id)
        })
      }
    }
    const deptTree = []
    initDeptTree(deptTree,"0")
    deptOptions.value = deptTree
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyId: undefined,
    department: [],
    staffCode: undefined,
    staffName: undefined,
    mobile: undefined
  },
  rules: {
    staffName: [{ required: true, message: "用户名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    mobile: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

function genderFormatter(row, column) {
  return row.gender === 1? '男':'女'
}
function deptFormatter(row, column) {
  if(row.department.length > 0) {
    for(let i = 0; i < deptList.value.length; i++) {
      if(deptList.value[i].id === row.department[0]) {
        return deptList.value[i].deptName
      }
    }
  }
}
/*选择公司事件*/
function handleCompanyChange(companyId) {
  queryParams.value.companyId = companyId
  queryParams.value.department = []
  getDeptList(companyId)
  getList()
}
/** 查询用户列表 */
function getList() {
  listStaff(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    userList.value = res.ds.content
    total.value = Number(res.ds.totalElements)
  });
}
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.department[0] = data.id
  handleQuery();
};
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  const staffIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户编号为"' + staffIds + '"的数据项？').then(function () {
    return delUser(staffIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 初始化部门数据 */
function initTreeData() {
  // 判断部门的数据是否存在，存在不获取，不存在则获取
  if (deptOptions.value === undefined) {
    // 查询公司部门
    getDeptList(queryParams.value.companyId)
  }
};
/** 重置操作表单 */
function reset() {
  form.value = {
    staffCode: undefined,
    staffName: undefined,
    mobile: undefined,
    position: undefined,
    gender: undefined,
    email: undefined,
    staffType: "1",
    enable: true,
    companyId: undefined,
    department: [],
    order:[],
    isLeaderInDept:[],
    directLeader:[]
  }
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加成员";
};
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  initTreeData();
  const staffId = row.id || ids.value;
  getStaff(staffId).then(res => {
    form.value = res.ds;
    open.value = true;
    title.value = "修改成员";
  });
};
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      form.value.department[0] = form.value.departmentId
      form.value.isLeaderInDept[0] = 0
      form.value.order[0] = 0
      form.value.companyId = company.value
      saveStaff(form.value).then(response => {
        if (form.value.id !== undefined) {
          proxy.$modal.msgSuccess("修改成功");
        } else {
          proxy.$modal.msgSuccess("新增成功");
        }
        open.value = false;
        getList();
      })
    }
  })
}
getCompanyList();
</script>
